package com.example.service;

import com.alibaba.fastjson.JSON;
import com.example.entity.Order;
import com.example.repository.StockRepository;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * @author shenxiang
 * @date 2020/11/14 21:20
 * @description
 */
@Service
@RocketMQMessageListener(topic = "seckill_queue",consumerGroup = "seckill_queue_consumer_grp")
public class SeckillConsumer implements RocketMQListener<Order> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StockRepository stockRepository;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Order order) {
        System.out.println("读取创建的订单信息:"+JSON.toJSONString(order));
        //将订单写入到表中
        if (orderService.getOneByOrderNo(order.getOrderNo()) != null){
            return;
        }
        // 看库存是否还有,没有的话记录日志
        if (stockRepository.getStock() == null || stockRepository.getStock() <= 0){
            order.setOrderDescription(order.getOrderDescription()+",库存不足");
            orderService.save(order);
            return;
        }
        //保存订单
        orderService.save(order);
        // 存一份消息到待支付检查队列
        Message message = MessageBuilder.withPayload(order).build();
        // 发一份消息到等待队列中去
        rocketMQTemplate.syncSend("seckill_queue_await_pay",message,rocketMQTemplate.getProducer().getSendMsgTimeout(),4);
    }
}
